package com.snatch.snatchmgr.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.snatch.common.constant.SnatchConstant;
import com.snatch.common.utils.DateUtil;
import com.snatch.common.vo.LiveMatch;
import com.snatch.common.vo.Matchinfo;
import com.snatch.common.vo.Playinfo;
import com.snatch.common.vo.RatioDataInput;
import com.snatch.common.vo.Result;
import com.snatch.common.vo.Sportinfo;
import com.snatch.common.vo.TradingItem;
import com.snatch.snatchmgr.constant.SystemConstant;
import com.snatch.snatchmgr.entity.db.ThirdLive;
import com.snatch.snatchmgr.entity.db.ThirdMatch;
import com.snatch.snatchmgr.entity.db.ThirdPlayinfo;
import com.snatch.snatchmgr.entity.db.ThirdTradingItem;
import com.snatch.snatchmgr.service.CrawlerDataService;
import com.snatch.snatchmgr.service.MatchDataService;
import com.snatch.snatchmgr.system.SystemData;

/**
 * 智能匹配数据服务类
 */
@Service
public class MatchDataServiceImpl implements MatchDataService {

	/**
	 * 联赛处理线程
	 */
	// private ExecutorService executorService =
	// Executors.newFixedThreadPool(100);
	private ExecutorService executorService = Executors.newCachedThreadPool();
	// 日志对象
	private Logger log = Logger.getLogger(MatchDataServiceImpl.class);
	
	@Autowired
	private BussinessDataConvert bdc;
	
	@Autowired
	private CrawlerDataService crawlerDataService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sbf.nodemanage.service.impl.MatchDataService#doParseXML(java.lang
	 * .String)
	 */

	@Override
	@SuppressWarnings({ "rawtypes" })
	public void doParseXML(RatioDataInput ratioDataInput) throws Exception {
		try {
			List<Sportinfo> sportinfos = ratioDataInput.getSportinfos();
			CountDownLatch latch = new CountDownLatch(sportinfos.size());
			for (Sportinfo sport : sportinfos) {
				try {
					RatioDataInput r = copyRatioData(ratioDataInput);
					executorService.execute(new ThreadMatch(latch,r,sport));
				} catch (RejectedExecutionException e) {
					log.info(
							"按联赛自动匹配赛事超时("
									+ SystemConstant.MATCH_DATA_OUT_TIME
									+ ")，强行中断:"
									+  "，来源："
									+ ratioDataInput + ":=>" + ratioDataInput,e);
				}
			}

			boolean excuteState = latch.await(SystemConstant.MATCH_DATA_OUT_TIME, TimeUnit.SECONDS);// 超时设置
			if (!excuteState) {
				executorService.shutdownNow();
				executorService = Executors.newCachedThreadPool();// 重新定义线程池
			}
		} catch (Exception e) {
			log.error("自动匹配出错:" + ratioDataInput, e);
		}
	}

	private RatioDataInput copyRatioData(RatioDataInput ratioDatainput) {
		RatioDataInput r = new RatioDataInput();
		r.setUserName(ratioDatainput.getUserName());
		r.setRatioType(ratioDatainput.getRatioType());
		r.setOnlyCode(ratioDatainput.getOnlyCode());
		r.setTaskCode(ratioDatainput.getTaskCode());
		r.setWebCode(ratioDatainput.getWebCode());
		r.setGameCode(ratioDatainput.getGameCode());
		r.setSnatchCost(ratioDatainput.getSnatchCost());
		r.setItemName(ratioDatainput.getItemName());
		r.setItemType(ratioDatainput.getItemType());
		return r;
	}
	
	
	@Override
	public void doDealRatioData(RatioDataInput ratioDataInput,Sportinfo sportinfo) {
		
		boolean isNormal = false;   // 标识传进来的第三方数据是否做为标准数据
		long sysUpdateTime = System.currentTimeMillis();// 更新时间
		boolean iscreate = false;
		
		if(SnatchConstant.HG_SNATCH_ITEM_STANDARD.equals(ratioDataInput.getItemName()) || SnatchConstant.HG_SNATCH_ITEM_FIRST.equals(ratioDataInput.getItemName())){
			//赛事创建与同步的权限
			iscreate = true;
		}
		/*
		 * long t2=System.currentTimeMillis(); log.info("解析报文步骤1=>前奏："+(t2-t1));
		 */
		Map<String, ThirdMatch> thirdMatchMap = SystemData.findAddThirdMatchs(ratioDataInput.getWebCode(), ratioDataInput.getGameCode(),ratioDataInput.getItemType());
		for (Matchinfo matchinfo : sportinfo.getMatchs()) {// 遍历赛事
			ThirdMatch thirdMatch = null;
			if(iscreate){
				// 内存第三方数据  //只有标准数据才能创建赛事
				thirdMatch = findAndAddThirdMatch(thirdMatchMap,ratioDataInput,matchinfo,sportinfo);// thirdData.get(league.getSelfID());//根据第三方联赛名称从第三方联赛
				thirdMatch.setSystemUpdateTime(sysUpdateTime);// 更新第三方赛事最后更新时间
			}else{
				String matchkey = SystemData.getMatchMapKey(sportinfo.getSelfID(), matchinfo.getMatchselfID());
				thirdMatch = thirdMatchMap.get(matchkey);
				if(null !=thirdMatch){
					//不相等则反向付一些属性
					matchinfo.setStartTime(DateUtil.format(thirdMatch.getStartTime(), SnatchConstant.MATCH_START_TIME));
				}
			}
			// 内存数据中获取第三方联赛对象
			if (null == thirdMatch)
				continue;
			// bobo 同步第三方联赛
			//syncThirdLeague(thirdLeague, league);
			// bobo 过滤赛事名称

			// 滚球用盘中来判断数据是否过期 bgin
			if ( thirdMatch.isValid() == false) {// 跳过已经被标识为无效的赛事
				log.info(thirdMatch.getMatchName()+ "赛事已转滚球，单式跳过不处理！");
				continue;
			}

			// 滚球用盘中来判断数据是否过期end
			// 将macth同步更新
			if(iscreate){
				syncThirdMatch(thirdMatch, matchinfo);
			}
				
			doDealHandicap(ratioDataInput, thirdMatch, matchinfo);
			if(null != matchinfo.getLiveMatch()){
				doDealLiveMatch(ratioDataInput,thirdMatch, matchinfo.getLiveMatch());
			}

			}
	}
	
	
	@Override
	public void doDealResultData(RatioDataInput ratioDataInput,
			Sportinfo sportinfo) {
		// TODO Auto-generated method stub
		for(Result result : sportinfo.getResults()){
			if(null == result.getTarget() || null == result.getLeagueSelfid() || null == result.getMatchSelfid() || null == result.getStartTime()) return;
			String livekey = SystemData.getLiveMatchMapKey(
					result.getLeagueSelfid(),result.getMatchSelfid());
			ThirdLive livedata = SystemData.findLiveData(ratioDataInput.getWebCode(),ratioDataInput.getGameCode(),livekey);
			if(null == livedata){
				ThirdMatch thirdMatch = crawlerDataService.findThirdMatch(result.getTarget(), result.getLeagueSelfid(), result.getMatchSelfid(),DateUtil.parseDate(result.getStartTime(), SnatchConstant.MATCH_START_TIME));
				livedata = bdc.getThirdLive(ratioDataInput, result);
				if(null != thirdMatch){
					livedata.setThirdMatchId(thirdMatch.getId());
				}
				SystemData.addLiveData(ratioDataInput.getWebCode(), ratioDataInput.getGameCode(), livekey, livedata);
				crawlerDataService.addThirdLive(livedata);
			}else{
				syncLiveResult(livedata, result);
			}
		
		}
	}
	/**
	 * 处理盘口信息
	 * @param ratioDataInput
	 * @param thirdMatch
	 * @param matchinfo
	 */
	private void doDealHandicap(RatioDataInput ratioDataInput,ThirdMatch thirdMatch,Matchinfo matchinfo){
		long time = System.currentTimeMillis();
		List<String> playkeys = filterPlay(ratioDataInput.getItemName(), thirdMatch);
		for (Playinfo playinfo : matchinfo.getPlayinfos()) {
			// 过滤掉未知的盘口
			if (playinfo.getName().equals("unknow"))
				continue;
			
			// 在滚球赛事中根据盘中来过滤掉不符合要求的盘口
			String piKey = playinfo.getSaveKey();// 由于以前数据结构不技持玩法key的唯一性，这里需要单独为玩法生成key// 由于以前数据结构不技持玩法key的唯一性，这里需要单独为玩法生成key
			playkeys.remove(piKey);
			ThirdPlayinfo thirdPlayinfo = findAndAddThirdPlayinfo(
					piKey, thirdMatch, playinfo);
			if (null == thirdPlayinfo)
				continue;
			// 第三方玩法记录最后更新时间
			thirdPlayinfo.setSystemUpdateTime(System.currentTimeMillis());
			thirdPlayinfo.setCloseSign(0);
			thirdPlayinfo.setValid(true);
			/*NormalPlayinfo normalPlayinfo = findAndAddNormalPlayinfo(
					piKey, isNormal, normalMatch, thirdPlayinfo);
			if (isNormal && null != normalPlayinfo) {
				normalPlayinfo.setSystemUpdateTime(sysUpdateTime);// 更新最后更新时间
			}*/
			/* if(null == normalPlayinfo) continue; */
			// --------------遍历交易项--------------
			doDealTradingItem(ratioDataInput, thirdPlayinfo, playinfo);
		}
		
		for(String playkey : playkeys){
			ThirdPlayinfo thirdPlayinfo = thirdMatch.getThirdPlayinfos().get(playkey);
			thirdPlayinfo.setCloseSign(thirdPlayinfo.getCloseSign()+1);
			if(SystemData.systemConfig.getCloseSignMax()<=thirdPlayinfo.getCloseSign()){
				thirdPlayinfo.setValid(false);
				thirdPlayinfo.setChangeTime(time);
				thirdMatch.setChangeTime(time);
			}
		}
	}
	
	
	/**
	 * 处理玩法赔率项  
	 * @param ratioDataInput
	 * @param thirdPlayinfo
	 * @param playinfo  
	 */
	private void doDealTradingItem(RatioDataInput ratioDataInput,ThirdPlayinfo thirdPlayinfo,Playinfo playinfo){
		long time = System.currentTimeMillis();
		for (TradingItem tradingItem : playinfo
				.getTradingItems()) {
			// boolean changeRatio=false;//标识交易项赔率是否发生变化
			// 获得第三方交易项
			String tiKey = playinfo.getGametime()
					+"_"+ tradingItem.getName();
			ThirdTradingItem thirdTradingItem = thirdPlayinfo
					.getThirdTradingItems().get(tiKey);
			if (thirdTradingItem == null) {// 第三方交易项不存在处理
				thirdTradingItem = bdc.getThirdTradingItem(
						tradingItem, ratioDataInput.getWebCode());
				thirdTradingItem.setThirdMatch(thirdPlayinfo.getThirdMatch());
				thirdTradingItem.setTradeGameCode(ratioDataInput.getGameCode());
				thirdTradingItem
						.setThirdPlayinfo(thirdPlayinfo);
				thirdTradingItem.setGametime(playinfo
						.getGametime());
				thirdTradingItem.setTradeGamestatus(ratioDataInput.getItemType());
				thirdTradingItem.setRatioType(ratioDataInput.getRatioType());// 设置赔率类型
				//bobo db
				/*crawlerDataService
						.addThirdTradingItem(thirdTradingItem);*/
				thirdPlayinfo.getThirdTradingItems().put(tiKey,
						thirdTradingItem);
			}
			if(thirdTradingItem.getRatio() != tradingItem.getRatio()){
				thirdTradingItem.setRatio(tradingItem.getRatio());// 更新赔率
				thirdTradingItem.getThirdPlayinfo().setChangeTime(time);
			}
			thirdTradingItem.setSystemUpdateTime(time);// 记录更新时间
			thirdTradingItem.setSelfID(tradingItem.getSelfID());// 更新交易项第三方编号
			
		}
	}
	
	
	public List<String> filterPlay(String itemName,ThirdMatch thirdMatch){
		List<String> playNames = new ArrayList<String>();
		if(SnatchConstant.HG_SNATCH_ITEM_STANDARD.equals(itemName)){
			Iterator<String> iterator =  thirdMatch.getThirdPlayinfos().keySet().iterator();
			while (iterator.hasNext()) {
				String playName = iterator.next();
				if(SystemData.isStandardPlay(playName)){
					playNames.add(playName);
				}
				
			}
		}
		return playNames;
	}
	
	/**
	 * 处理过关
	 */
	public void doDealPass(RatioDataInput ratioDataInput,ThirdMatch thirdMatch,Matchinfo matchinfo){
		List<String> playkeys = new ArrayList<String>();
		playkeys.addAll(thirdMatch.getThirdPlayinfos().keySet());
		
		for (Playinfo playinfo : matchinfo.getPlayinfos()) {
			// 过滤掉未知的盘口
			if (playinfo.getName().equals("unknow"))
				continue;
			// 在滚球赛事中根据盘中来过滤掉不符合要求的盘口
			String piKey = playinfo.getSaveKey();// 由于以前数据结构不技持玩法key的唯一性，这里需要单独为玩法生成key// 由于以前数据结构不技持玩法key的唯一性，这里需要单独为玩法生成key
			playkeys.remove(piKey);
			ThirdPlayinfo thirdPlayinfo = thirdMatch.getThirdPlayinfos().get(piKey);
			if (null == thirdPlayinfo)
				continue;
			thirdPlayinfo.setBunch(playinfo.isBunch());
		}
		
		for(String playkey : playkeys){
			ThirdPlayinfo thirdPlayinfo = thirdMatch.getThirdPlayinfos().get(playkey);
			thirdPlayinfo.setBunch(false);
		}
	}

	
	private void doDealLiveMatch(RatioDataInput ratioDataInput,ThirdMatch thirdMatch,LiveMatch liveMatch){
		String matchkey = SystemData.getLiveMatchMapKey(liveMatch.getLeagueSelfID(), liveMatch.getMatchSelfID());
		
		ThirdLive thirdlive = SystemData.findLiveData(ratioDataInput.getWebCode(),ratioDataInput.getGameCode(),matchkey);
		if(null == thirdlive){
			thirdlive = bdc.getLiveData(ratioDataInput,liveMatch);
			thirdlive.setThirdMatchId(thirdMatch.getId());
			thirdlive.setStartTime(thirdMatch.getStartTimestr());
			crawlerDataService.addThirdLive(thirdlive);
			SystemData.addLiveData(ratioDataInput.getWebCode(),ratioDataInput.getGameCode(),matchkey,thirdlive);
		}
		// 将macth同步更新
		syncLiveData(thirdlive, liveMatch);
	}
	
	private void syncLiveData(ThirdLive livedata,LiveMatch liveMatch){
		if(SnatchConstant.FOOTBALL.equals(livedata.getGameCode())){
			syncLiveFootball(livedata, liveMatch);
		}else if(SnatchConstant.BASKETBALL.equals(livedata.getGameCode())){
			syncLiveBasketball(livedata, liveMatch);
		}else if(SnatchConstant.TENNIS.equals(livedata.getGameCode())){
			syncLiveTennis(livedata, liveMatch);
		}
		/*
		
		// 中场休息时赛事数据中设置的安全球状态为未知
		*/
	}
	
	private void syncLiveFootball(ThirdLive footballLive,LiveMatch liveMatch){
		footballLive.setShowTime(liveMatch.getShowTime());
		footballLive.setStatus(liveMatch.getStatus());
		footballLive.setCloseStatus(liveMatch.getCloseStatus());
		//进球逻辑
		footballLive.setHomeGoal(liveMatch.getHomeGoal());
		footballLive.setAwayGoal(liveMatch.getAwayGoal());
		footballLive.setHomeYc(liveMatch.getHomeYC());
		footballLive.setAwayYc(liveMatch.getAwayYC());
		
		if (footballLive.getStatus() == 0) {
			footballLive.setShowTime("0");
		}
		String[] footballhalf = SystemData.systemConfig.getFootballhalf();
		if(null != footballhalf){
			for(String filterStr:footballhalf){
				if(filterStr.indexOf(liveMatch.getShowTime())>-1){
					footballLive.setHhtGoal(liveMatch.getHomeGoal());
					footballLive.setHatGoal(liveMatch.getAwayGoal());
				}
			}
		}
		
	}
	
	/**
	 * 同步篮球
	 * @param liveBasketball
	 * @param liveMatch
	 */
	private void syncLiveBasketball(ThirdLive liveBasketball,LiveMatch liveMatch){
		
		liveBasketball.setShowTime(liveMatch.getShowTime());		//时间只能减。不会加，除非状态增加，如果状态没增加 主动增加状 态 而状态只增加不会减
		liveBasketball.setStatus(liveMatch.getStatus());
		liveBasketball.setCloseStatus(liveMatch.getCloseStatus());
		liveBasketball.setHomeGoal(liveMatch.getHomeGoal());
		liveBasketball.setAwayGoal(liveMatch.getAwayGoal());
		//篮球 -1未开赛 1为第一节 2为第二节 3为第三节 4为第4节 5为加时    0中场
		if(1==liveMatch.getStatus()){
			liveBasketball.setOnehGoal(liveMatch.getHomeGoal());
			liveBasketball.setOneaGoal(liveMatch.getAwayGoal());
			
			liveBasketball.setHhtGoal(liveMatch.getHomeGoal());
			liveBasketball.setHatGoal(liveMatch.getAwayGoal());
		}else if(2==liveMatch.getStatus()){
			liveBasketball.setTwohGoal(liveMatch.getHomeGoal()-liveBasketball.getOnehGoal());
			liveBasketball.setTwoaGoal(liveMatch.getAwayGoal()-liveBasketball.getOneaGoal());
			
			liveBasketball.setHhtGoal(liveMatch.getHomeGoal());
			liveBasketball.setHatGoal(liveMatch.getAwayGoal());
		}else if(3==liveMatch.getStatus()){
			liveBasketball.setThreehGoal(liveMatch.getHomeGoal()-liveBasketball.getTwohGoal()-liveBasketball.getOnehGoal());
			liveBasketball.setThreeaGoal(liveMatch.getAwayGoal()-liveBasketball.getTwoaGoal()-liveBasketball.getOneaGoal());
			
		}else if(4==liveMatch.getStatus()){
			liveBasketball.setFourhGoal(liveMatch.getHomeGoal()-liveBasketball.getThreehGoal()-liveBasketball.getTwohGoal()-liveBasketball.getOnehGoal());
			liveBasketball.setFouraGoal(liveMatch.getAwayGoal()-liveBasketball.getThreeaGoal()-liveBasketball.getTwoaGoal()-liveBasketball.getOneaGoal());
			
		}else if(5==liveMatch.getStatus()){
			liveBasketball.setEthGoal(liveMatch.getHomeGoal()-liveBasketball.getFourhGoal()-liveBasketball.getThreehGoal()-liveBasketball.getTwohGoal()-liveBasketball.getOnehGoal());
			liveBasketball.setEtaGoal(liveMatch.getAwayGoal()-liveBasketball.getFouraGoal()-liveBasketball.getThreeaGoal()-liveBasketball.getTwoaGoal()-liveBasketball.getOneaGoal());
		}
	}
	
	
	/**
	 * 同步网球
	 * @param liveTennis
	 * @param liveMatch
	 */
	private void syncLiveTennis(ThirdLive liveTennis,LiveMatch liveMatch){
		
		liveTennis.setNowServer(liveMatch.getNowServer());
		
		liveTennis.setCloseStatus(liveMatch.getCloseStatus());
		liveTennis.setHomeGoal(liveMatch.getHomeGoal());
		liveTennis.setAwayGoal(liveMatch.getAwayGoal());
		
		liveTennis.setHboutCoal(liveMatch.getHboutCoal());
		liveTennis.setAboutCoal(liveMatch.getAboutCoal());
		liveTennis.setHscoreCoal(liveMatch.getHscoreCoal());
		liveTennis.setAscoreCoal(liveMatch.getAscoreCoal());
	
	}
	
	
	/**
	 * 同步网球
	 * @param liveTennis
	 * @param liveMatch
	 */

	private void syncLiveResult(ThirdLive liveresult, Result result) {
		boolean change = false;

		if (result.getStatus() != liveresult.getStatus()) {
			liveresult.setStatus(result.getStatus());
			change = true;
		}


		if (null != result.getMatchError()) {
			if (!result.getMatchError().equals(liveresult.getMatchError())) {
				liveresult.setMatchError(result.getMatchError());
				change = true;
			}
		}

		if (null != result.getLeagueName()) {
			if (!result.getLeagueName().equals(liveresult.getLeagueName())) {
				liveresult.setLeagueName(result.getLeagueName());
				change = true;
			}
		}

		if (null != result.getMatchName()) {
			if (!result.getMatchName().equals(liveresult.getMatchName())) {
				liveresult.setMatchName(result.getMatchName());
				change = true;
			}
		}

		if (null != result.getStartTime()) {
			if (!result.getStartTime().equals(liveresult.getStartTime())) {
				liveresult.setStartTime(result.getStartTime());
				change = true;
			}
		}

		if (result.getHomeGoal() != liveresult.getHomeGoal()) {
			liveresult.setHomeGoal(result.getHomeGoal());
			change = true;
		}

		if (result.getHhtGoal() != liveresult.getHhtGoal()) {
			liveresult.setHhtGoal(result.getHhtGoal());
			change = true;
		}

		if (result.getShrhGoal() != liveresult.getShrhGoal()) {
			liveresult.setShrhGoal(result.getShrhGoal());
			change = true;
		}

		if (result.getOnehGoal() != liveresult.getOnehGoal()) {
			liveresult.setOnehGoal(result.getOnehGoal());
			change = true;
		}

		if (result.getTwohGoal() != liveresult.getTwohGoal()) {
			liveresult.setTwohGoal(result.getTwohGoal());
			change = true;
		}

		if (result.getThreehGoal() != liveresult.getThreehGoal()) {
			liveresult.setThreehGoal(result.getThreehGoal());
			change = true;
		}

		if (result.getFourhGoal() != liveresult.getFourhGoal()) {
			liveresult.setFourhGoal(result.getFourhGoal());
			change = true;
		}

		if (result.getFivehGoal() != liveresult.getFivehGoal()) {
			liveresult.setFivehGoal(result.getFivehGoal());
			change = true;
		}

		if (result.getSixhGoal() != liveresult.getSixhGoal()) {
			liveresult.setSixhGoal(result.getSixhGoal());
			change = true;
		}

		if (result.getSevenhGoal() != liveresult.getSevenhGoal()) {
			liveresult.setSevenhGoal(result.getSevenhGoal());
			change = true;
		}

		if (result.getEthGoal() != liveresult.getEthGoal()) {
			liveresult.setEthGoal(result.getEthGoal());
			change = true;
		}

		if (result.getScorehGoal() != liveresult.getScorehGoal()) {
			liveresult.setScorehGoal(result.getScorehGoal());
			change = true;
		}

		if (result.getAwayGoal() != liveresult.getAwayGoal()) {
			liveresult.setAwayGoal(result.getAwayGoal());
			change = true;
		}

		if (result.getHatGoal() != liveresult.getHatGoal()) {
			liveresult.setHatGoal(result.getHatGoal());
			change = true;
		}

		if (result.getShraGoal() != liveresult.getShraGoal()) {
			liveresult.setShraGoal(result.getShraGoal());
			change = true;
		}

		if (result.getOneaGoal() != liveresult.getOneaGoal()) {
			liveresult.setOneaGoal(result.getOneaGoal());
			change = true;
		}

		if (result.getTwoaGoal() != liveresult.getTwoaGoal()) {
			liveresult.setTwoaGoal(result.getTwoaGoal());
			change = true;
		}

		if (result.getThreeaGoal() != liveresult.getThreeaGoal()) {
			liveresult.setThreeaGoal(result.getThreeaGoal());
			change = true;
		}

		if (result.getFouraGoal() != liveresult.getFouraGoal()) {
			liveresult.setFouraGoal(result.getFouraGoal());
			change = true;
		}

		if (result.getFiveaGoal() != liveresult.getFiveaGoal()) {
			liveresult.setFiveaGoal(result.getFiveaGoal());
			change = true;
		}

		if (result.getSixaGoal() != liveresult.getSixaGoal()) {
			liveresult.setSixaGoal(result.getSixaGoal());
			change = true;
		}

		if (result.getSevenaGoal() != liveresult.getSevenaGoal()) {
			liveresult.setSevenaGoal(result.getSevenaGoal());
			change = true;
		}

		if (result.getEtaGoal() != liveresult.getEtaGoal()) {
			liveresult.setEtaGoal(result.getEtaGoal());
			change = true;
		}

		if (result.getScoreaGoal() != liveresult.getScoreaGoal()) {
			liveresult.setScoreaGoal(result.getScoreaGoal());
			change = true;
		}
		
		if(change){
			crawlerDataService.updThirdLive(liveresult);
		}

	}
	
	/**
	 * 查找或添加第三方赛事
	 * 
	 * @param thirdLeague
	 * @param match
	 * @param dataType
	 * @return
	 */
	private ThirdMatch findAndAddThirdMatch(Map<String, ThirdMatch> thirdMatchMap,RatioDataInput ratioDataInput,
			Matchinfo matchinfo,Sportinfo sportinfo) {
		ThirdMatch thirdMatch = null;
		try {
			String matchkey = SystemData.getMatchMapKey(sportinfo.getSelfID(),matchinfo.getMatchselfID());
			thirdMatch = thirdMatchMap.get(matchkey);
			if (null == thirdMatch) {
				
				thirdMatch = bdc.getThirdMatch(ratioDataInput,matchinfo, sportinfo);
				/**
				 * bobo  保存插入时不会出程序上的错误
				 */
				thirdMatchMap.put(matchkey, thirdMatch);
				crawlerDataService.addThirdMatch(thirdMatch);
				//bobo db
				//crawlerDataService.addThirdMatch(thirdMatch);

				// bobo 设置第三方赛事对应的标准赛事名称
				/*String newName1 = teamService.getMatchName(
						thirdMatch.getName(), thirdMatch.getTarget(),
						thirdLeague.getId(), false);*/
				/*log.debug("第三方赛事名称换为标准名称：" + thirdMatch.getNormalName() + "==>"
						+ newName1);
				thirdMatch.setNormalName(newName1);*/
			}
		} catch (Exception e) {
			log.error("查找或添加第三方赛事报错", e);
		}
		return thirdMatch;
	}
	

	/**
	 * 查找或添加第三方玩法
	 * 
	 * @param piKey
	 * @param thirdMatch
	 * @param playinfo
	 * @return
	 */
	private ThirdPlayinfo findAndAddThirdPlayinfo(String piKey,
			ThirdMatch thirdMatch, Playinfo playinfo) {
		ThirdPlayinfo thirdPlayinfo = thirdMatch.getThirdPlayinfos().get(piKey);
		if (thirdPlayinfo == null) {// 第三方玩法不存在处理
			thirdPlayinfo = bdc.getThirdPlayinfo(playinfo);
			// 第三方玩法存入内存
			thirdMatch.getThirdPlayinfos().put(piKey, thirdPlayinfo);
		} else {
			// 更新玩法id，皇冠会改玩法id
			thirdPlayinfo.setHandicap(playinfo.getHandicap());
			thirdPlayinfo.setSelfID(playinfo.getSelfID());
		}
		return thirdPlayinfo;
	}


	/**
	 * 同步第三方赛事
	 * 
	 * @param thirdMatch
	 * @param match
	 */
	private void syncThirdMatch(ThirdMatch thirdMatch, Matchinfo match) {
		boolean ischange = false;
		if (null != thirdMatch && null != match) {
			if (!thirdMatch.getMatchName().equals(match.getMatchName())) {
				String oldName = thirdMatch.getMatchName();
				thirdMatch.setMatchName(match.getMatchName());
				log.info("第三方赛事名称改变：" + oldName + "==>" + thirdMatch.getMatchName());
				ischange = true;
			}
			if (!match.getStartTime().equals(thirdMatch.getStartTimestr())) { // 第三方同名赛事存在，判断开赛时间是否已经更改
				thirdMatch.setStartTime(DateUtil.parseDate(match.getStartTime(), SnatchConstant.MATCH_START_TIME));// 更新开赛时间
				thirdMatch.setStartTimestr(match.getStartTime());
				ischange = true;
			}
			if(!match.getMatchType().equals(thirdMatch.getMatchType())){
				//bobo如果早餐转单式  或单式转滚球，所有数据收盘再创建新的盘口
				thirdMatch.setMatchType(match.getMatchType());
				ischange = true;
			}
			if(match.isBunch()!=thirdMatch.isBunch()){
				//bobo如果早餐转单式  或单式转滚球，所有数据收盘再创建新的盘口
				thirdMatch.setBunch(match.isBunch());
				ischange = true;
			}
			if(match.getBunchNumber()!=thirdMatch.getBunchNumber()){
				//bobo如果早餐转单式  或单式转滚球，所有数据收盘再创建新的盘口
				thirdMatch.setBunchNumber(match.getBunchNumber());
				ischange = true;
			}
			if(!match.getMatchName().equals(thirdMatch.getMatchName())){
				//bobo如果早餐转单式  或单式转滚球，所有数据收盘再创建新的盘口
				thirdMatch.setMatchName(match.getMatchName());//(match.getBunchNumber());
				ischange = true;
			}
			if (ischange) {
				crawlerDataService.updThirdMatch(thirdMatch);
			}
		}
	}


	class ThreadMatch<T> implements Runnable {
		private CountDownLatch latch;
		private RatioDataInput ratioDataInput;
		private Sportinfo sport;

		ThreadMatch(CountDownLatch latch, RatioDataInput ratioDataInput,Sportinfo sport) {
			this.latch = latch;
			this.ratioDataInput = ratioDataInput;
			this.sport = sport;
		}

		@Override
		public void run() {
			try {
				if(SnatchConstant.HG_SNATCH_ITEM_RESULT.equals(ratioDataInput.getItemName())){
					doDealResultData(ratioDataInput,sport);
				}else{
					doDealRatioData(ratioDataInput,sport);
				}
				
			} catch (Exception e) {
				log.info("多线程按联赛自动匹配出错:" + ratioDataInput.toString(), e);
			} finally {
				latch.countDown();
			}
		}
	}

	

	/**
	 * 根据不同的第三方合并数据 该方法适合lj sb
	 * 
	 * @param list
	 * @param type
	 * @return
	 */
	/*
	 * private List<Sportinfo> combineSporttinfoOne(List<Sportinfo> list,String
	 * type){ List<Match> matchs = new ArrayList<Match>(); Map<String,Integer>
	 * matchIndex = new HashMap<String,Integer>(); for(Sportinfo sportinfo :
	 * list){ matchs.addAll(sportinfo.getMatchs());
	 * sportinfo.getMatchs().clear(); for(Match match : matchs){
	 * if(!matchIndex.containsKey(match.getName()+match.getMatchFlag())){
	 * matchIndex.put(match.getName()+match.getMatchFlag(),
	 * sportinfo.getMatchs().size()); sportinfo.getMatchs().add(match); }else{
	 * Match temMatch =
	 * sportinfo.getMatchs().get(matchIndex.get(match.getName()+
	 * match.getMatchFlag()));
	 * temMatch.getPlayinfos().addAll(match.getPlayinfos()); } } matchs.clear();
	 * matchIndex.clear(); } matchs = null; matchIndex = null; return list; }
	 *//**
	 * 根据不同的第三方合并数据 该方法适合hg
	 * 
	 * @param list
	 * @param type
	 * @return
	 */
	/*
	 * private List<Sportinfo> combineSporttinfoTwo(List<Sportinfo> list,String
	 * type){
	 * 
	 * List<Sportinfo> sportflag = new ArrayList<Sportinfo>();
	 * Map<String,Integer>sportIndex = new HashMap<String,Integer>();
	 * sportflag.addAll(list); list.clear(); for(Sportinfo sportinfo :
	 * sportflag){ if(!sportIndex.containsKey(sportinfo.getName())){
	 * sportIndex.put(sportinfo.getName(), sportflag.size());
	 * list.add(sportinfo); }else{ Sportinfo temSportinfo =
	 * list.get(sportIndex.get(sportinfo.getName()));
	 * temSportinfo.getMatchs().addAll(sportinfo.getMatchs()); } }
	 * 
	 * sportflag.clear(); sportIndex.clear();
	 * 
	 * List<Match> matchs = new ArrayList<Match>(); Map<String,Integer>
	 * matchIndex = new HashMap<String,Integer>(); for(Sportinfo sportinfo :
	 * list){ matchs.addAll(sportinfo.getMatchs());
	 * sportinfo.getMatchs().clear(); for(Match match : matchs){
	 * if(!matchIndex.containsKey(match.getName()+match.getMatchFlag())){
	 * matchIndex.put(match.getName()+match.getMatchFlag(),
	 * sportinfo.getMatchs().size()); sportinfo.getMatchs().add(match); }else{
	 * Match temMatch =
	 * sportinfo.getMatchs().get(matchIndex.get(match.getName()+
	 * match.getMatchFlag()));
	 * temMatch.getPlayinfos().addAll(match.getPlayinfos()); } } matchs.clear();
	 * matchIndex.clear(); } matchs = null; matchIndex = null; sportflag = null;
	 * sportIndex = null; return list; }
	 */

	
	public static void main(String[] args) throws DocumentException {
		// long t = System.currentTimeMillis();
		// for(int i=0;i<9999;i++){
		// MD5.getMD5("aaaaaaaaaa");
		// }
		// System.out.println((System.currentTimeMillis()-t));
		// System.out.println(MD5.getMD5("aaaaaaaaaa12"));

		/*
		 * List<String> listsp = new ArrayList<String>(); for(int
		 * i=0;i<9999;i++){
		 * listsp.add("asdffffffffffffffffffffffffffffffffffffff" +
		 * "ffffffffffffffffffffffffffffffasdfasdfdas41sdf656sdf464we" +
		 * "r64asf46as6df6saf46sadfasffasdfasfasdf4sadf" +
		 * "64as6d5f456asdf46as4df6asdffffffffffffffffffffffffffff"); } long
		 * times = System.currentTimeMillis(); StringBuffer spbuffer = new
		 * StringBuffer(); for(int i=0;listsp!=null &&i<listsp.size();i++){
		 * spbuffer.append(listsp.get(i));
		 * spbuffer.append("--------------------------"
		 * +i+"-----------------------------"); } try {
		 * FileUtils.writeStringToFile(new
		 * File(SYSConstant.saveDataPath+"_"+SYSConstant
		 * .SNATCH_ITEM_SP_CODE+".xml"), spbuffer.toString()); } catch
		 * (IOException e) { }
		 * System.out.println((System.currentTimeMillis()-times));
		 */
	}

	
}
